package com.musicsonar.android.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.Toast;

import com.musicsonar.android.adapter.ResultSearchAdapter;
import com.musicsonar.android.adapter.TouchListView;
import com.musicsonar.android.bean.Song;
import com.musicsonar.android.utils.SongsManager;

public class PlayListActivity extends ListActivity {

	protected TouchListView mListView;
	protected ResultSearchAdapter mAdapter;

	private static PlayListActivity me;

	// Songs list
	public List<Map<String, Object>> songsList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.playlist);

		mListView = (TouchListView)getListView();
		mListView.setDropListener(onDrop);
		mListView.setRemoveListener(onRemove);
		mListView.setInvalidPositionListener(onInvalidPosition);

		registerForContextMenu(mListView);

		me = this;

		drawPlayList();
	}

	@SuppressWarnings("deprecation")
	private void drawPlayList(){
		TabPlayListActivity tabPlayListActivity = (TabPlayListActivity)getParent();
		// get all songs from sdcard
		this.songsList = convertBeanToMap(SongsManager.getPlayList(tabPlayListActivity.getTabHost().getCurrentTab()).getSongList());

		// Adding menuItems to ListView
		mAdapter = new ResultSearchAdapter(me, songsList, R.layout.playlist_item, new String[] { "songImage", "songTitle", "songDuration", "index", "index" }, new int[] { R.id.songImage, R.id.songTitle, R.id.songDuration, R.id.btnPlaySong, R.id.btnDeleteSong }, true);

		setListAdapter(mAdapter);
		if(songsList.size() == 0){
			Toast.makeText(this, getText(R.string.playlist_nosong_message), Toast.LENGTH_LONG).show();
		}
	}

	private TouchListView.DropListener onDrop=new TouchListView.DropListener() {
		public void drop(int from, int to) {
			List<Map<String, Object>> data = (List<Map<String, Object>>) mAdapter.getData();
			Map<String, Object> item = (Map<String, Object>)data.get(from);
			data.remove(from);
			data.add(to, item);
        	for(int i = 0; i < data.size(); i++){
        		Map<String, Object> _data = (Map<String, Object>)data.get(i);
        		_data.put("index", String.valueOf(i));
        		data.set(i, _data);
        	}
        	SongsManager.savePlayList(data);
			songsList = data;
			mAdapter.notifyDataSetChanged();
		}
	};

	private TouchListView.RemoveListener onRemove=new TouchListView.RemoveListener() {
		public void remove(int which) {
			List<Map<String, Object>> data = (List<Map<String, Object>>) mAdapter.getData();
			data.remove(which);
        	for(int i = 0; i < data.size(); i++){
        		Map<String, Object> _data = (Map<String, Object>)data.get(i);
        		_data.put("index", String.valueOf(i));
        		data.set(i, _data);
        	}
        	SongsManager.savePlayList(data);
			songsList = data;
			mAdapter.notifyDataSetChanged();
		}
	};

	private TouchListView.InvalidPositionListener onInvalidPosition=new TouchListView.InvalidPositionListener() {
		
		public void invalidPosition() {
			if(songsList == null || songsList.size() == 0){
				Intent i = new Intent(getApplicationContext(), SearchActivity.class);
				startActivityForResult(i, 100);
			}
		}
	}; 

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                && keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            Log.d("CDA", "onKeyDown Called");
            onBackPressed();
        }
        //KeyEvent.KEYCODE_MENU
        return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
        Log.d("CDA", "onBackPressed Called");
        Intent setIntent = new Intent(me.getApplicationContext(), MusicSonarActivity.class);
        startActivity(setIntent); 

        return;
	}

	private List<Map<String, Object>> convertBeanToMap(List<Song> songs){
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		if(songs.size() > 0){
			for(Song song : songs){
				Map<String, Object> item = new HashMap<String, Object>();
				item.put("index", song.getIndex().toString());
				item.put("segundos", song.getSegundos().toString());
				item.put("songDuration", song.getSongDuration());
				item.put("songImage", song.getSongImage());
				item.put("songPath", song.getSongPath());
				item.put("songTitle", song.getSongTitle());
				item.put("songYT", song.getSongYT());
				result.add(item);
			}
		}
		return result;
	}

	/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@SuppressWarnings("unchecked")
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
        	List<Map<String, Object>> listSelected = (List<Map<String, Object>>)data.getExtras().getSerializable("songSelected");
        	if(listSelected != null && listSelected.size() > 0){
        		for(Map<String, Object> item : listSelected){
                	if(item != null){
                		item.put("index", String.valueOf(songsList.size()));
                		songsList.add(item);
                	}
        		}
            	try{
            		SongsManager.savePlayList(songsList);
            	}catch(Exception e){
            		e.printStackTrace();
            	}
            	mAdapter = new ResultSearchAdapter(this, songsList, R.layout.playlist_item, new String[] { "songImage", "songTitle", "songDuration", "index", "index" }, new int[] { R.id.songImage, R.id.songTitle, R.id.songDuration, R.id.btnDeleteSong, R.id.btnPlaySong }, true);

        		setListAdapter(mAdapter);
        	}
        }
    }
}